package com.exp2.caloriedaily

import android.R
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import java.text.SimpleDateFormat
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.borax12.materialdaterangepicker.date.DatePickerDialog
import com.exp2.caloriedaily.adapter.CalorieListAdapter
import com.exp2.caloriedaily.service.CalorieService
import com.exp2.caloriedaily.utils.DateUtils
import com.google.android.material.internal.ContextUtils.getActivity
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter
import com.jjoe64.graphview.series.BarGraphSeries
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_manage_calorie.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.yesButton
import java.text.ParsePosition
import java.util.*


class MainActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {

    var startTime = ""
    var endTime = ""

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(com.exp2.caloriedaily.R.layout.activity_main)

        textView5.setOnClickListener {
            showDatePickerDialog(it)
        }

        textView25.setOnClickListener {
            val intent = Intent(this@MainActivity, ManageCalorieActivity::class.java)
            startActivity(intent)
        }

        textView6.setOnClickListener {
            queryData()
        }


    }

    override fun onDateSet(
        view: DatePickerDialog?,
        year: Int,
        monthOfYear: Int,
        dayOfMonth: Int,
        yearEnd: Int,
        monthOfYearEnd: Int,
        dayOfMonthEnd: Int
    ) {

        //开始时间的时间戳
        if (monthOfYear+1<10&&dayOfMonth<10){
            startTime = "$year-0${monthOfYear + 1}-0$dayOfMonth"
        }else if (monthOfYear+1>=10&&dayOfMonth<10){
            startTime = "$year-${monthOfYear + 1}-0$dayOfMonth"
        }else if (monthOfYear+1<10&&dayOfMonth>=10){
            startTime = "$year-0${monthOfYear + 1}-$dayOfMonth"
        }else{
            startTime = "$year-${monthOfYear + 1}-$dayOfMonth"
        }

        if (monthOfYearEnd+1<10&&dayOfMonthEnd<10){
            endTime = "$yearEnd-0${monthOfYearEnd + 1}-0$dayOfMonthEnd"
        }else if (monthOfYearEnd+1>=10&&dayOfMonthEnd<10){
            endTime = "$yearEnd-${monthOfYearEnd + 1}-0$dayOfMonthEnd"
        }else if (monthOfYearEnd+1<10&&dayOfMonthEnd>=10){
            endTime = "$yearEnd-0${monthOfYearEnd + 1}-$dayOfMonthEnd"
        }else{
            endTime = "$yearEnd-${monthOfYearEnd + 1}-$dayOfMonthEnd"
        }

        val timeStart = DateUtils.getTimeStart(startTime)
        //结束时间的时间戳
        val timeEnd = DateUtils.getTimeStart(endTime)

        textView4.text = startTime
        if (timeStart?.toLong()!! > timeEnd?.toLong()!!) {
            textView7.text = textView4.text
            endTime=startTime
        } else {
            textView7.text = endTime
        }

        Log.d(
            "&&&&&&&&&&&",
            "【" + year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日" + "】——到——【" +
                    yearEnd + "年" + (monthOfYearEnd + 1) + "月" + dayOfMonthEnd + "日】"
        )

        Log.d("&&&&&&&&&&&", "【开始时间戳：" + timeStart + "】——到——【" + "结束时间戳：" + timeEnd + "】")

    }

    private fun showDatePickerDialog(view: View) {
        val now = Calendar.getInstance()
        val dpd: DatePickerDialog = DatePickerDialog.newInstance(
            this@MainActivity,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
        )

        dpd.show(getFragmentManager(), "Datepickerdialog")
    }

    @SuppressLint("SimpleDateFormat")
    private fun queryData(): Unit? {
        if (startTime == "" || endTime == "") {
            return null
        }
        val calorieService = CalorieService.getInstance(this)
        val data = calorieService.query("date between '${startTime}' and '${endTime}' ")
        if (data.isEmpty()) {
            alert("查询日期没有数据!"){yesButton {  }}.show()
            return null
        }
        if (data.size==1){
            alert("日期：${data[0].date}    卡路里:${data[0].calorie}千卡") {
                title="当前查询的数据小于2"
                yesButton {  }
            }.show()
            return null
        }

        val dataPoint = Array<DataPoint>(data.size) {
            DataPoint(0.0, 0.0)
        }

        for (d in data.indices) {
            val date:Date=SimpleDateFormat("yyyy-MM-dd").parse(data[d].date)
            dataPoint[d] = DataPoint(date, data[d].calorie!!.toDouble())
            Log.d("dataPoint is",dataPoint[d].toString())
        }

        val series = LineGraphSeries<DataPoint>(dataPoint)


        val graph = findViewById<GraphView>(com.exp2.caloriedaily.R.id.graph)

        graph.removeAllSeries()
        graph.addSeries(series)

        graph.gridLabelRenderer.labelFormatter = DateAsXAxisLabelFormatter(this)
        graph.gridLabelRenderer.numHorizontalLabels = data.size+1
        graph.viewport.isScalable = true

        graph.title = "单位:千卡"


        graph.viewport.setMinX(SimpleDateFormat("yyyy-MM-dd").parse(data[0].date).time.toDouble())
        graph.viewport.setMaxX(SimpleDateFormat("yyyy-MM-dd").parse(data.last().date).time.toDouble())
        graph.viewport.isXAxisBoundsManual = true
        //graph.gridLabelRenderer.isHumanRounding = false




        return null
    }

}